package com.yzr.common.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache2 myCache = new MyCache2();

        for (int i = 1; i < 6; i++) {
            final int key = i;
            new Thread(() -> {
                myCache.put(key + "", key + "");
            }, String.valueOf(i)).start();
        }

        for (int i = 1; i < 6; i++) {
            final int key = i;
            new Thread(() -> {
                myCache.get(key + "");
            }, String.valueOf(i)).start();
        }
    }
}

class MyCache2 {

    private Map<String, Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object v) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println("线程" + Thread.currentThread().getName() + "写入");
            map.put(key, v);
            System.out.println("线程" + Thread.currentThread().getName() + "写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println("线程" + Thread.currentThread().getName() + "读取");
            Object o = map.get(key);
            System.out.println("线程" + Thread.currentThread().getName() + "读取完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

}

class MyCache {
    private Map<String, Object> map = new HashMap<>();

    public void put(String key, Object v) {
        System.out.println("线程" + Thread.currentThread().getName() + "写入");
        map.put(key, v);
        System.out.println("线程" + Thread.currentThread().getName() + "写入完成");
    }

    public void get(String key) {
        System.out.println("线程" + Thread.currentThread().getName() + "读取");
        Object o = map.get(key);
        System.out.println("线程" + Thread.currentThread().getName() + "读取完成");
    }

}